<script lang="ts" setup>
// #region 引入包, 函数和组件
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Check,
  User,
  Lock,
  Message,
  Phone,
  Calendar,
  MapLocation,
  Camera,
  UserFilled,
} from '@element-plus/icons-vue'
// #endregion

// #region // 使用模块(仓库、路由、父组件参数函数)
const router = useRouter()
// #endregion

// #region // 变量
const registerFormRef = ref<FormInstance>()
// 删除重复声明，只保留类型完善后的声明
// #endregion

// 类型定义
interface RegisterForm {
  username: string
  password: string
  confirmPassword: string
  email: string
  phone: string
  birthday: string
  address: string
  gender: string
  hobbies: string[]
  avatar: string
}

import type { FormInstance, FormRules } from 'element-plus'

const form = reactive<RegisterForm>({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  birthday: '',
  address: '',
  gender: '',
  hobbies: [],
  avatar: '',
})

const formRules = reactive<FormRules<RegisterForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: unknown, value: string, callback: (error?: string | Error) => void) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
  ],
  birthday: [{ required: true, message: '请选择生日', trigger: 'change' }],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, message: '地址至少5个字符', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
})

const backgroundImages = ref<string[]>([
  'https://picsum.photos/id/1039/1920/1080',
  'https://picsum.photos/id/1040/1920/1080',
  'https://picsum.photos/id/1041/1920/1080',
])
const currentBackgroundIndex = ref<number>(0)
// #endregion

// #region // 函数
const handleRegister = () => {
  if (!registerFormRef.value) return
  registerFormRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm('注册成功，是否前往登录页面？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '留在本页',
        type: 'success',
        center: true,
      }).then(() => {
        router.push('/login')
      })
    } else {
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

const switchBackground = () => {
  currentBackgroundIndex.value = (currentBackgroundIndex.value + 1) % backgroundImages.value.length
}

// 修正头像上传类型和本地预览
const handleAvatarUpload = (uploadFile: {
  url?: string
  response?: { url?: string }
  raw?: File
}) => {
  if (uploadFile.url) {
    form.avatar = uploadFile.url
  } else if (uploadFile.response && uploadFile.response.url) {
    form.avatar = uploadFile.response.url
  } else if (uploadFile.raw) {
    const reader = new FileReader()
    reader.onload = (e: ProgressEvent<FileReader>) => {
      if (e.target && typeof e.target.result === 'string') {
        form.avatar = e.target.result
      }
    }
    reader.readAsDataURL(uploadFile.raw)
  }
  // 立即刷新图片
  setTimeout(() => {}, 0)
  ElMessage.success('头像上传成功')
}
// #endregion

// #region // 生命周期和vue函数
onMounted(() => {
  // 设置背景图自动切换，每5秒切换一次
  setInterval(switchBackground, 5000)
})
// #endregion
</script>

<template>
  <div
    class="register-container"
    :style="{ backgroundImage: `url(${backgroundImages[currentBackgroundIndex]})` }"
  >
    <div class="register-card">
      <div class="register-title">注册</div>
      <el-form ref="registerFormRef" :model="form" :rules="formRules" class="register-form">
        <!-- 头像上传 -->
        <el-form-item class="avatar-upload">
          <el-upload
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarUpload"
            :before-upload="() => false"
          >
            <div class="avatar-container">
              <img v-if="form.avatar" :src="form.avatar" class="avatar-img" />
              <div v-else class="avatar-placeholder">
                <Camera class="avatar-icon" />
                <span class="avatar-text">点击上传头像</span>
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item prop="username" label="用户名">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            v-model="form.confirmPassword"
            placeholder="请确认密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item prop="email" label="邮箱">
          <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
            size="large"
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item prop="phone" label="手机号">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            :prefix-icon="Phone"
            size="large"
          />
        </el-form-item>

        <!-- 生日 -->
        <el-form-item prop="birthday" label="生日">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="请选择生日"
            :prefix-icon="Calendar"
            size="large"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item prop="address" label="地址">
          <el-input
            v-model="form.address"
            placeholder="请输入地址"
            :prefix-icon="MapLocation"
            size="large"
          />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item prop="gender" label="性别">
          <el-radio-group v-model="form.gender" :prefix-icon="UserFilled" size="large">
            <el-radio value="male">男</el-radio>
            <el-radio value="female">女</el-radio>
            <el-radio value="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item class="register-button">
          <el-button
            type="primary"
            size="large"
            class="register-btn"
            @click="handleRegister"
            :icon="Check"
          >
            注册
          </el-button>
        </el-form-item>

        <!-- 登录链接 -->
        <div class="login-link">
          <el-link type="primary" @click="router.push('/login')">已有账号？去登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  transition: background-image 1s ease-in-out;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 500px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.18);
  padding: 40px 36px 32px 36px;
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.register-title {
  text-align: center;
  font-size: 28px;
  font-weight: 700;
  color: #165dff;
  margin-bottom: 32px;
  letter-spacing: 2px;
}

.register-form {
  .el-form-item {
    margin-bottom: 22px;
    label {
      font-size: 15px;
      color: #333;
      font-weight: 500;
      margin-bottom: 6px;
      display: inline-block;
    }
  }
}

.avatar-upload {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-container {
  width: 120px;
  height: 120px;
  min-height: 120px;
  min-width: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 2.5px solid #e0e0e0;
  cursor: pointer;
  transition:
    border-color 0.3s,
    box-shadow 0.3s;
  background: #f8faff;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.08);
  &:hover {
    border-color: #165dff;
    box-shadow: 0 4px 16px rgba(22, 93, 255, 0.15);
  }
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  border: 2px solid #e0e0e0;
  background: #fff;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.08);
  display: block;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #b0b3b8;
}

.avatar-icon {
  font-size: 36px;
  margin-bottom: 8px;
}

.el-input,
.el-date-picker {
  font-size: 16px;
}

.el-input__wrapper,
.el-date-editor {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(22, 93, 255, 0.04);
}

.el-radio-group,
.el-checkbox-group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 8px 0;
}

.el-radio,
.el-checkbox {
  margin-right: 18px;
  font-size: 15px;
  color: #444;
}

.el-radio__input.is-checked + .el-radio__label,
.el-checkbox__input.is-checked + .el-checkbox__label {
  color: #165dff;
  font-weight: 600;
}

.register-button {
  margin-top: 28px;
}

.register-btn {
  width: 100%;
  background: linear-gradient(90deg, #165dff 0%, #409eff 100%);
  border: none;
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.1);
  transition:
    background 0.3s,
    box-shadow 0.3s;
  &:hover {
    background: linear-gradient(90deg, #409eff 0%, #165dff 100%);
    box-shadow: 0 4px 16px rgba(22, 93, 255, 0.18);
  }
}

.login-link {
  text-align: center;
  margin-top: 24px;
  font-size: 15px;
}

@media (max-width: 600px) {
  .register-card {
    padding: 18px 6px 12px 6px;
    max-width: 98vw;
  }
  .register-title {
    font-size: 20px;
  }
}
</style>
